package com.qf.smsplatform.strategy.service.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.service.Strategy;
import com.qf.smsplatform.strategy.service.api.CacheService;
import com.qf.smsplatform.strategy.utils.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @Author: LeeRui
 * 2021/1/27 下午 9:18
 * 限流1小时策略
 **/
@Service(value = "limitOneDay")
@Slf4j
public class LimitOneHourStrategy implements Strategy {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("【限流1小时策略】 限流1小时策略开始执行！！！");
        //获取客户ID和目标手机号，与常量中limit组成key
        int clientID = standardSubmit.getClientID();
        String mobile = standardSubmit.getDestMobile();
        String key = CacheConstants.CACHE_PREFIX_SMS_LIMIT+clientID+":"+mobile;

        //获取发送时间的毫秒值和5分钟之前的毫秒值
        long sendTime = standardSubmit.getSendTime().getTime();
        long fiveMinuteBefore = sendTime - 1000 * 60 * 60;

        //调用缓存模块，查询5分钟之内发送过几条短信
        Set<Object> zrangebyscore = cacheService.zrangebyscore(key, fiveMinuteBefore, sendTime);

        //判断五分钟内发送信息次数
        if (zrangebyscore.size() >= 5){
            log.info("【限流1小时策略】 发送短信次数上限，限流1小时策略校验失败！！！");
            //向MQ发送消息和报告
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            pushMsgUtil.pushReport(standardSubmit,StrategyConstants.STRATEGY_ERROR_LIMIT);
            return false;
        }

        //成功
        log.info("【限流1小时策略】 限流1小时策略校验成功！！！");
        return true;
    }
}
